package v5

import (
	"fmt"
	"log"
	v4 "mindonmap/api/v4"
	"mindonmap/models"
	"mindonmap/pkgs/e"
	"mindonmap/pkgs/setting"
	"mindonmap/pkgs/util"
	"mindonmap/validation"
	"net/http"
	"strconv"
	"time"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
	"github.com/segmentio/ksuid"
)

type Mindmap struct {
	ID             int                    `json:"-"`
	Mindid         string                 `json:"mindid"`
	Acid           int                    `json:"acid"`
	Filename       string                 `json:"filename"`
	Mapdata        map[string]interface{} `json:"mapdata"`
	Image          string                 `json:"image"`
	State          int                    `json:"state"`
	Sharestate     int                    `json:"sharestate"`
	Orders         int                    `json:"orders"`
	IsAi           int                    `json:"is_ai"`
	IsAiResult     int                    `json:"is_ai_result"`
	AiKey          string                 `json:"ai_key"`
	Lang           string                 `json:"lang"`
	CreatePlatform string                 `json:"create_platform"`
	SavePlatform   string                 `json:"Save_platform"`
}

type ShareData struct {
	Shareid string                 `json:"shareid"`
	Image   string                 `json:"image"`
	Mapdata map[string]interface{} `json:"mapdata"`
}
type MindRestore struct {
	Mindid string `json:"mindid"`
	T      string `json:"t"`
}

// 获取多个已删除脑图
func GetMindMapsDel(c *gin.Context) {
	data := make(map[string]interface{})
	var maps Mindmap
	valid := validation.Validation{}

	if err := c.BindJSON(&maps); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.SUCCESS
		data["lists"] = models.GetDelMindMapsV5(util.GetPage(c), setting.PageSize, Userid)
		data["total"] = models.GetMindMapDelTotalV5(Userid)

	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 获取多个脑图
func GetMindMaps(c *gin.Context) {
	data := make(map[string]interface{})
	var maps Mindmap
	valid := validation.Validation{}
	Userid, err := GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	// if maps.State == 3 {
	// 	mapsdata["state"] = maps.State
	// } else {
	// 	mapsdata["state"] = maps.State
	// 	mapsdata["acid"] = Userid
	// }

	var sorts string
	switch maps.Orders {
	case 1:
		sorts = "createtime desc"
	case 2:
		sorts = "createtime desc"
	case 3:
		sorts = "createtime desc"
	case 4:
		sorts = "createtime desc"
	default:
		sorts = "createtime desc"
	}

	code := e.INVALID_PARAMS
	fmt.Println(valid.HasErrors())
	if !valid.HasErrors() {

		code = e.SUCCESS
		data["lists"] = models.GetMindMapslistV5(util.GetPage(c), setting.PageSize, Userid, sorts)
		data["total"] = models.GetMindMapTotalV5(Userid)

	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// CopyMind 拷贝单个文件
func CopyMind(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.Mindid, "mindid").Message("不能为空")

	// 判断权益
	Userid, err := GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}
	var total = MindMapTotal(Userid)
	pc := NewPrivilegeController()
	var isvip = IsVip(c)
	var CheckPriv bool
	if isvip {
		CheckPriv = pc.CheckPrivilege("vip", "cloud_storage_limit", total)
	} else {
		CheckPriv = pc.CheckPrivilege("free", "cloud_storage_limit", total)
	}
	if !CheckPriv {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_PERMISSION,
			"msg":  e.GetMsg(e.ERROR_AUTH_PERMISSION),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		if models.ExistMindMapByID(json.Mindid, Userid) {
			models.CopyMindMap(json.Mindid)
			code = e.SUCCESS
		} else {
			code = e.ERROR_NOT_EXIST_ARTICLE
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": "",
	})
}

// 新增脑图
func AddMindMap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	var total = v4.MindMapTotal(Userid)
	pc := NewPrivilegeController()
	var isvip = v4.IsVip(c)
	var user_status = 0
	var CheckPriv bool
	if isvip {
		CheckPriv = pc.CheckPrivilege("vip", "cloud_storage_limit", total)
		user_status = 1
	} else {
		CheckPriv = pc.CheckPrivilege("free", "cloud_storage_limit", total)
	}
	if !CheckPriv {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_PERMISSION,
			"msg":  e.GetMsg(e.ERROR_AUTH_PERMISSION),
			"data": make(map[string]interface{}),
		})
		return
	}

	Mindid := ksuid.New().String()
	code := e.INVALID_PARAMS
	data := make(map[string]interface{})
	if !models.ExistMindMapByMindID(Mindid) {

		image := util.WriteFile(strconv.Itoa(Userid), json.Mindid, json.Image)
		if len(image) > 0 {
			var aws3 = setting.GetAWSS3()
			S3Host := aws3.S3Host
			image = S3Host + image
		}
		data["mindid"] = Mindid
		data["acid"] = Userid
		data["lang"] = json.Lang
		data["filename"] = json.Filename
		data["image"] = image
		data["is_ai"] = json.IsAi
		data["is_ai_result"] = json.IsAiResult
		data["ai_key"] = json.AiKey
		data["state"] = 0
		data["create_platform"] = json.CreatePlatform
		data["user_status"] = user_status
		models.AddMindMap2(data)
		//data["id"]=models.GetMindMapID(Mindid)
		code = e.SUCCESS
	} else {
		data["mindid"] = Mindid
		data["acid"] = Userid
		data["filename"] = json.Filename
		data["mapdata"] = json.Mapdata
		//data["id"]=models.GetMindMapID(json.Mindid)
		code = e.ERROR_EXIST_PARAMS
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 保存脑图
func EditMindMap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}
	code := e.INVALID_PARAMS
	if models.ExistMindMapByID(json.Mindid, Userid) {
		image := util.WriteFile(strconv.Itoa(Userid), json.Mindid, json.Image)
		if len(image) > 0 {
			var aws3 = setting.GetAWSS3()
			S3Host := aws3.S3Host
			image = S3Host + image
		}

		mapdata := util.WriteTxt(strconv.Itoa(Userid), json.Mindid, json.Mapdata)
		if len(mapdata) > 0 {
			var aws3 = setting.GetAWSS3()
			S3Host := aws3.S3Host
			mapdata = S3Host + mapdata
		}
		// fmt.Println("json:::::", json.SavePlatform)

		data := make(map[string]interface{})
		data["mapdata"] = mapdata
		data["modifietime"] = time.Now().Unix()
		data["image"] = image
		data["save_platform"] = json.SavePlatform
		claims := jwt.ExtractClaims(c)
		util.WriteLog("UserJWT：" + claims["username"].(string) + "|" + claims["userId"].(string) + ":")
		models.EditMindMap(json.Mindid, data)
		code = e.SUCCESS
		// datas := make(map[string]interface{})
		// // 离开时则更新版本1
		// if json.State == 0 {
		// 	if !models.ExistMindVersionBySourceID(json.Mindid) {
		// 		datas["pid"] = json.Mindid
		// 		datas["acid"] = Userid
		// 		datas["mapdata"] = mapdata
		// 		datas["state"] = 0
		// 		datas["image"] = image
		// 		datas["version"] = 2
		// 		models.AddMindVersion(datas)
		// 	} else {
		// 		datas["pid"] = json.Mindid
		// 		datas["acid"] = Userid
		// 		datas["mapdata"] = mapdata
		// 		datas["image"] = image
		// 		datas["modifietime"] = time.Now().Unix()
		// 		datas["version"] = 2
		// 		models.EditMindVersionSource(json.Mindid, datas)
		// 	}
		// }
	} else {
		code = e.ERROR_NOT_EXIST_ARTICLE
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

// 分享编辑新增脑图
func EditSaveMindMap(c *gin.Context) {
	var json ShareData
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	var total = v4.MindMapTotal(Userid)
	pc := NewPrivilegeController()
	var isvip = v4.IsVip(c)
	var CheckPriv bool
	if isvip {
		CheckPriv = pc.CheckPrivilege("vip", "cloud_storage_limit", total)
	} else {
		CheckPriv = pc.CheckPrivilege("free", "cloud_storage_limit", total)
	}
	if !CheckPriv {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_PERMISSION,
			"msg":  e.GetMsg(e.ERROR_AUTH_PERMISSION),
			"data": make(map[string]interface{}),
		})
		return
	}
	Mindid := ksuid.New().String()
	code := e.INVALID_PARAMS
	data := make(map[string]interface{})
	if !models.ExistMindMapByMindID(Mindid) {
		shareData := models.GetMindShare(json.Shareid)
		if shareData.IsEdit == 0 {
			c.JSON(http.StatusOK, gin.H{
				"code": e.ERROR_AUTH_PERMISSION,
				"msg":  e.GetMsg(e.ERROR_AUTH_PERMISSION),
				"data": data,
			})
			return
		}
		// if shareData.Acid == Userid {
		// 	c.JSON(http.StatusOK, gin.H{
		// 		"code": e.ERROR_ADD,
		// 		"msg":  e.GetMsg(e.ERROR_ADD),
		// 		"data": data,
		// 	})
		// 	return
		// }

		mindmap := models.GetMindMapShare(shareData.Pid)
		image := util.WriteFile(strconv.Itoa(Userid), mindmap.Mindid, json.Image)
		if len(image) > 0 {
			var aws3 = setting.GetAWSS3()
			S3Host := aws3.S3Host
			image = S3Host + image
		}
		data["mindid"] = Mindid
		data["acid"] = Userid
		data["filename"] = mindmap.Filename
		data["image"] = image
		data["state"] = 0
		if mindmap.Version == 1 {
			data["mapdata"] = mindmap.Mapdata
			models.AddMindMap(data)
		} else {
			mapdata := util.WriteTxt(strconv.Itoa(Userid), mindmap.Mindid, json.Mapdata)
			if len(mapdata) > 0 {
				var aws3 = setting.GetAWSS3()
				S3Host := aws3.S3Host
				mapdata = S3Host + mapdata
			}
			fmt.Print("mapdata:::", mapdata)
			data["mapdata"] = mapdata
			models.ShareAddMindMap(data)
		}
		//data["id"]=models.GetMindMapID(Mindid)
		code = e.SUCCESS
	} else {
		shareData := models.GetMindShare(json.Shareid)
		mindmap := models.GetMindMapShare(shareData.Pid)
		data["mindid"] = Mindid
		data["acid"] = Userid
		data["filename"] = mindmap.Filename
		data["mapdata"] = json.Mapdata
		//data["id"]=models.GetMindMapID(json.Mindid)
		code = e.ERROR_EXIST_PARAMS
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 获取单个脑图
func GetMindMap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}
	models.SaveUserLog(Userid, 0, time.Now().Unix())
	var isvip = IsVip(c)
	if isvip {
		models.SaveActiveLog(Userid, 1, 1)
	} else {
		models.SaveActiveLog(Userid, 0, 1)
	}

	valid := validation.Validation{}
	valid.Required(json.Mindid, "mindid").Message("不能为空")

	code := e.INVALID_PARAMS
	var data interface{}
	if !valid.HasErrors() {
		if models.ExistMindMapByID(json.Mindid, Userid) {
			data = models.GetMindMap(json.Mindid)
			code = e.SUCCESS
		} else {
			code = e.ERROR_NOT_EXIST_ARTICLE
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 脑图重命名
func RenameMindmap(c *gin.Context) {
	var json Mindmap
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}
	code := e.INVALID_PARAMS
	if models.ExistMindMapByID(json.Mindid, Userid) {
		data := make(map[string]interface{})
		data["filename"] = json.Filename
		models.EditMindMap(json.Mindid, data)
		code = e.SUCCESS
	} else {
		code = e.ERROR_NOT_EXIST_ARTICLE
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})
}

func MindonmapLike(c *gin.Context) {
	type Request struct {
		MindID string `json:"mind_id" binding:"required"`
		Status *int   `json:"status" binding:"required,oneof=0 1"`
	}

	var req Request
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS) + ": " + err.Error(),
			"data": nil,
		})
		return
	}
	// 确保Status被设置
	if req.Status == nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  "status字段是必需的",
			"data": nil,
		})
		return
	}

	// 使用指针解引用获取值
	status := *req.Status

	// 获取用户ID
	userID, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": nil,
		})
		return
	}

	// 准备要保存的数据
	likeData := models.MindLikes{
		Acid:       userID,
		MindId:     req.MindID,
		Status:     status,
		CreateTime: time.Now().Unix(),
	}

	// 保存点赞信息
	if err := models.SaveMindMapLike(likeData); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": e.ERROR,
			"msg":  "保存点赞信息失败: " + err.Error(),
			"data": nil,
		})
		return
	}

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"code": e.SUCCESS,
		"msg":  e.GetMsg(e.SUCCESS),
		"data": nil,
	})
}
